#!/bin/bash
set -euo pipefail

COMMIT=$(git rev-parse HEAD)
TAG=$(git describe --exact-match --abbrev=0 --tags "${COMMIT}" 2> /dev/null || true)
BRANCH=$(git branch | grep \* | cut -d ' ' -f2 | sed -e 's/[^a-zA-Z0-9+=._:/-]*//g' || true)
OUTPUT_PATH=${OUTPUT_PATH:-"bin/kube-aws"}
VERSION=""
ETCD_VERSION="v3.4.9"
KUBERNETES_VERSION="v1.16.10"

if [ -z "$TAG" ]; then
        [[ -n "$BRANCH" ]] && VERSION="${BRANCH}/"
	VERSION="${VERSION}${COMMIT:0:8}"
else
	VERSION=$TAG
fi

# check for changed files (not untracked files)
if [ -n "$(git diff --shortstat 2> /dev/null | tail -n1)" ]; then
    VERSION="${VERSION}+dirty"
fi

echo "Building kube-aws ${VERSION} (default Kubernetes version ${KUBERNETES_VERSION})"

printf 'Checking existence of the `packr` command that is used for embedding files into the resulting binary...'
if ! which packr 1>/dev/null; then
  echo not found. installing...
  go get -u github.com/gobuffalo/packr/packr
  echo 'Installed `packr`.'
else
  echo "found. Skipped installation."
fi

packr -vz

if [[ ! "${BUILD_GOOS:-}" == "" ]];then
  export GOOS=$BUILD_GOOS
fi
if [[ ! "${BUILD_GOARCH:-}" == "" ]];then
  export GOARCH=$BUILD_GOARCH
fi
go build -ldflags "-X github.com/kubernetes-incubator/kube-aws/pkg/model.VERSION=${VERSION} -X github.com/kubernetes-incubator/kube-aws/pkg/api.KUBERNETES_VERSION=${KUBERNETES_VERSION} -X github.com/kubernetes-incubator/kube-aws/pkg/api.ETCD_VERSION=${ETCD_VERSION}" -a -tags netgo -installsuffix netgo -o "$OUTPUT_PATH" ./
